using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

public class StartMenu : MonoBehaviour {
	public bool debug = false;
	
	public NetworkStart networkstart;
	private bool startMenuActive	= false;
	private GUIDuctTape ductTape;
	private GUIHealthBar healthBar;
	
	//Start Menu
	public float startMenuScale		= 1;
	private float oldStartMenuScale;
	public Texture2D startButtonTexture;
	public Vector2 startButtonPosition;
	public Texture2D settingsTexture;
	public Vector2 settingsPosition;
	public Texture2D exitButtonTexture;
	public Vector2 exitButtonPosition;
	public Texture2D helpButtonTexture;
	public Vector2 helpButtonPosition;
	public Texture2D creditsButtonTexture;
	public Vector2 creditsButtonPosition;
	
	public float slideTimer = 1;
	
	//Settings Menu
	public Texture2D volumeHighTexture;
	public Texture2D volumeLowTexture;
	public Texture2D resolutionLowTexture;
	public Texture2D resolutionHighTexture;
	public Texture2D qualityLowTexture;
	public Texture2D qualityHighTexture;
	public Texture2D saveButtonTexture;
	public Texture2D trashButtonTexture;

	private float settingsVolume;
	private float settingsResolution;
	private float settingsQuality;
	
	// Help Menu
	public Vector2 backFromHelpMenuPosition;
	public Texture2D helpScreenTexture;
	public Texture2D helpBackgroundTexture;
	
	//Credits
	public Vector2 backFromCreditsPosition;
	public Texture2D creditsScreenTexture;
	
	//Other
	public Texture2D backButtonTexture;
	public MovieTexture bgMovie;
	public float helpAndCreditsSize = 90;
	public Texture2D[] hatTextures;
	public Texture2D isReadyTexture;
	public Texture2D notReadyTexture;
	
	private enum Menu {MAIN = 1,SETTINGS,HELP,CREDITS};
	private Menu menu = Menu.MAIN;

	private bool fullScreen = true;
	private List<bool> playersReady = new List<bool>();
	private bool selfReady = false;
	
	//EndGame
	public float gameLength = 100f;
	private float gameTimeElapsed = 0f;
	private bool endgameable = true;
	
	void Awake(){
		Screen.SetResolution(Screen.currentResolution.width,Screen.currentResolution.height,fullScreen);	
	}
	
	void Start () {
		oldStartMenuScale = startMenuScale;
		
		for (int i = 0; i < Screen.resolutions.Length; i++){
			if (Screen.resolutions[i].Equals(Screen.currentResolution))
				settingsResolution = i;
		}
		
		settingsQuality = QualitySettings.GetQualityLevel();
		settingsVolume	= AudioListener.volume;
		
		if (bgMovie != null)
			bgMovie.loop = true;
		
		Vector2 clampedPosition;
		Vector2 oldPosition;
		foreach (FieldInfo fi in this.GetType().GetFields()){
			if (fi.FieldType == typeof(Texture2D)){
				if (fi.GetValue(this).ToString() == "null"){
					Texture2D newTexture = new Texture2D(100,100);
					newTexture.Apply();
					fi.SetValue(this,newTexture);
				}
			}
			if (fi.FieldType == typeof(Vector2)){
				oldPosition = (Vector2)fi.GetValue(this);
				clampedPosition = new Vector2(Mathf.Clamp(oldPosition.x,0,100),Mathf.Clamp(oldPosition.y,0,100));
				fi.SetValue(this,clampedPosition);
			}
		}
		
		if  (this.GetComponent<GUIDuctTape>() != null){
			ductTape = this.GetComponent<GUIDuctTape>();
			ductTape.setDisplay(false);	
		}
		if  (this.GetComponent<GUIHealthBar>() != null){
			healthBar = this.GetComponent<GUIHealthBar>();
			healthBar.setDisplay(false);
		}
	
	}
	
	void OnGUI(){
		if(debug)
			GUI.Box(new Rect(300,50,100,20),gameTimeElapsed.ToString());
		
		if (startMenuActive){
			

			
			startMenuScale = oldStartMenuScale * Screen.height/480;
			if (bgMovie != null){
				GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),bgMovie,ScaleMode.ScaleAndCrop);
				if (!bgMovie.isPlaying)
					bgMovie.Play();
			}
					//	GUI.Box(new Rect(-1,-1,Screen.width+1,Screen.height+1),"","box");
			// Connection boxes
			if (Network.isServer){
				float connectionBoxSize = Screen.height/8;
				while (playersReady.Count < Network.connections.Length)
					playersReady.Add(false);
				for (int i = 0; i < Network.connections.Length; i++){
					//GUI.Label(new Rect(Screen.width-connectionBoxSize*Network.connections.Length,0,connectionBoxSize,connectionBoxSize),Network.connections[i].ipAddress.ToString() + "\n Ready = " + playersReady[i] + ".","box");	
					GUI.DrawTexture(new Rect(Screen.width-connectionBoxSize*Network.connections.Length,0,connectionBoxSize,connectionBoxSize),hatTextures[i],ScaleMode.ScaleToFit);
					if (playersReady[i])
						GUI.DrawTexture(new Rect(Screen.width-connectionBoxSize*Network.connections.Length,0,connectionBoxSize,connectionBoxSize),isReadyTexture,ScaleMode.ScaleToFit);
					else
						GUI.DrawTexture(new Rect(Screen.width-connectionBoxSize*Network.connections.Length,0,connectionBoxSize,connectionBoxSize),notReadyTexture,ScaleMode.ScaleToFit);
				}
			}
			
			/// ---------------------------------------------------------------
			//	START MENU
			// ---------------------------------------------------------------
			if (menu == Menu.MAIN){
				
				// Start Button
				if (GUI.Button(new Rect(Screen.width*startButtonPosition.x/100-startMenuScale*startButtonTexture.width/2,Screen.height*startButtonPosition.y/100-startMenuScale*startButtonTexture.height/2,startMenuScale*startButtonTexture.width,startMenuScale*startButtonTexture.height),startButtonTexture,GUIStyle.none)){
					if (Network.isServer){
						selfReady = true;
						menu = Menu.HELP;
					}
					else if (Network.isClient) {
						networkView.RPC ("setReady", RPCMode.Server, true,Network.player.ipAddress);
						menu = Menu.HELP;
						selfReady = true;
					}
				}
				
				//Settings Menu Button
				if (GUI.Button(new Rect(Screen.width*settingsPosition.x/100-startMenuScale*settingsTexture.width/2,Screen.height*settingsPosition.y/100-startMenuScale*settingsTexture.height/2,startMenuScale*settingsTexture.width,startMenuScale*settingsTexture.height),settingsTexture,GUIStyle.none)){
					menu = Menu.SETTINGS;
				}
				// Help Menu Button
				if (GUI.Button(new Rect(Screen.width*helpButtonPosition.x/100-startMenuScale*helpButtonTexture.width/2,Screen.height*helpButtonPosition.y/100-startMenuScale*helpButtonTexture.height/2,startMenuScale*helpButtonTexture.width,startMenuScale*helpButtonTexture.height),helpButtonTexture,GUIStyle.none)){
					menu = Menu.HELP;
				}
				// Exit Button
				if (GUI.Button(new Rect(Screen.width*exitButtonPosition.x/100-startMenuScale*exitButtonTexture.width/2,Screen.height*exitButtonPosition.y/100-startMenuScale*exitButtonTexture.height/2,startMenuScale*exitButtonTexture.width,startMenuScale*exitButtonTexture.height),exitButtonTexture,GUIStyle.none)){
					Application.Quit();
				}
				// Credits Button
				if (GUI.Button(new Rect(Screen.width*creditsButtonPosition.x/100-startMenuScale*creditsButtonTexture.width/2,Screen.height*creditsButtonPosition.y/100-startMenuScale*creditsButtonTexture.height/2,startMenuScale*creditsButtonTexture.width,startMenuScale*creditsButtonTexture.height),creditsButtonTexture,GUIStyle.none)){
					menu = Menu.CREDITS;
				}
			}
			// ---------------------------------------------------------------
			//	SETTINGS MENU
			// ---------------------------------------------------------------
			else if (menu == Menu.SETTINGS){
				
				// Positions of elements in settings menu
				float settingsWidth 	= 75f;
				float settingsDistance	= 5f;
				float barAndIconSpace 	= 5f;
				float settingsHeight 	= 20f;
				float iconSpace 		= 20f;
				
				settingsWidth 		= Screen.width/100 * settingsWidth;
				settingsDistance 	= Screen.height/100 * settingsDistance;
				settingsHeight 		= Screen.height/100 * settingsHeight;
				iconSpace 			= settingsWidth/100 * iconSpace;
				barAndIconSpace 	= settingsWidth/100 * barAndIconSpace;
				
				// Resolution Settings		
				GUI.BeginGroup(new Rect((Screen.width-settingsWidth)/2,settingsDistance,settingsWidth,settingsHeight),""/*GUIStyle.none*/,"box");
					GUI.DrawTexture(new Rect(0,0,iconSpace,settingsHeight),resolutionLowTexture,ScaleMode.ScaleToFit);
					GUI.DrawTexture(new Rect(settingsWidth-iconSpace,0,iconSpace,settingsHeight),resolutionHighTexture,ScaleMode.ScaleToFit);
					settingsResolution = (int)GUI.HorizontalSlider(new Rect(iconSpace + barAndIconSpace,settingsHeight/2-10,settingsWidth-barAndIconSpace*2-iconSpace*2,10),settingsResolution,0,Screen.resolutions.Length-1);
				GUI.EndGroup();
				
				// Quality Settings		
				GUI.BeginGroup(new Rect((Screen.width-settingsWidth)/2,settingsDistance*2+settingsHeight,settingsWidth,settingsHeight),""/*GUIStyle.none*/,"box");
					GUI.DrawTexture(new Rect(0,0,iconSpace,settingsHeight),qualityLowTexture,ScaleMode.ScaleToFit);
					GUI.DrawTexture(new Rect(settingsWidth-iconSpace,0,iconSpace,settingsHeight),qualityHighTexture,ScaleMode.ScaleToFit);
					settingsQuality = (int)GUI.HorizontalSlider(new Rect(iconSpace + barAndIconSpace,settingsHeight/2-10,settingsWidth-barAndIconSpace*2-iconSpace*2,10),settingsQuality,0,QualitySettings.names.Length-1);
				GUI.EndGroup();
				
				// Volume Settings
				GUI.BeginGroup(new Rect((Screen.width-settingsWidth)/2,settingsDistance*3 + settingsHeight*2,settingsWidth,settingsHeight),""/*GUIStyle.none*/,"box");
					GUI.DrawTexture(new Rect(0,0,iconSpace,settingsHeight),volumeLowTexture,ScaleMode.ScaleToFit);
					GUI.DrawTexture(new Rect(settingsWidth-iconSpace,0,iconSpace,settingsHeight),volumeHighTexture,ScaleMode.ScaleToFit);
					settingsVolume = GUI.HorizontalSlider(new Rect(iconSpace + barAndIconSpace,settingsHeight/2-10,settingsWidth-barAndIconSpace*2-iconSpace*2,10),settingsVolume,0,1);
				GUI.EndGroup();
				
				
				GUI.BeginGroup(new Rect((Screen.width-settingsWidth)/2,settingsDistance*4 + settingsHeight*3,settingsWidth,settingsHeight),GUIStyle.none);
				
					// Back Button
					if (GUI.Button(new Rect(0,0,iconSpace,settingsHeight),backButtonTexture,GUIStyle.none)){
						menu = Menu.MAIN;
						for (int i = 0; i < Screen.resolutions.Length; i++){
							if (Screen.resolutions[i].Equals(Screen.currentResolution))
								settingsResolution = i;
						} 
						settingsQuality = QualitySettings.GetQualityLevel();
						settingsVolume	= AudioListener.volume;
					}
				
					// Trash Button
					if (GUI.Button(new Rect(settingsWidth/2-iconSpace/2,0,iconSpace,settingsHeight),trashButtonTexture,GUIStyle.none)){
						for (int i = 0; i < Screen.resolutions.Length; i++){
							if (Screen.resolutions[i].Equals(Screen.currentResolution))
								settingsResolution = i;
						} 
						settingsQuality = QualitySettings.GetQualityLevel();
						settingsVolume	= AudioListener.volume;
					}
				
					//Save Button
					if (GUI.Button(new Rect(settingsWidth-iconSpace,0,iconSpace,settingsHeight),saveButtonTexture,GUIStyle.none)){
						Screen.SetResolution(Screen.resolutions[(int)settingsResolution].width,Screen.resolutions[(int)settingsResolution].height,fullScreen);
						QualitySettings.SetQualityLevel((int)settingsQuality);
						AudioListener.volume = settingsVolume;
					}
				
				GUI.EndGroup();
				
			}
			// ---------------------------------------------------------------
			//	HELP MENU
			// ---------------------------------------------------------------
			else if (menu == Menu.HELP){
				//GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),helpBackgroundTexture,ScaleMode.ScaleAndCrop);
				GUI.DrawTexture(new Rect(Screen.width*(1-helpAndCreditsSize/100)/2,Screen.height*(1-helpAndCreditsSize/100)/2,Screen.width*helpAndCreditsSize/100,Screen.height*helpAndCreditsSize/100),helpScreenTexture,ScaleMode.ScaleToFit);
				if (allReady() && Network.isServer){
					//networkView.RPC ("startClient", RPCMode.All,null);
					networkstart.networkView.RPC("startGameRPC",RPCMode.AllBuffered,null);
					//startClient();
				}
				else if (!selfReady){
					if (GUI.Button(new Rect(Screen.width/100*backFromHelpMenuPosition.x-startMenuScale*backButtonTexture.width/2,Screen.height/100*backFromHelpMenuPosition.y-startMenuScale*backButtonTexture.height/2,startMenuScale*backButtonTexture.width,startMenuScale*backButtonTexture.height),backButtonTexture,GUIStyle.none))
					menu = Menu.MAIN;
				}
				
			}
			// ---------------------------------------------------------------
			//	CREDITS MENU
			// ---------------------------------------------------------------
			else if (menu == Menu.CREDITS){

				GUI.DrawTexture(new Rect(Screen.width*(1-helpAndCreditsSize/100)/2,Screen.height*(1-helpAndCreditsSize/100)/2,Screen.width*helpAndCreditsSize/100,Screen.height*helpAndCreditsSize/100),creditsScreenTexture,ScaleMode.ScaleToFit);
				if (GUI.Button(new Rect(Screen.width/100*backFromCreditsPosition.x-startMenuScale*backButtonTexture.width/2,Screen.height/100*backFromCreditsPosition.y-startMenuScale*backButtonTexture.height/2,startMenuScale*backButtonTexture.width,startMenuScale*backButtonTexture.height),backButtonTexture,GUIStyle.none))
					menu = Menu.MAIN;
			}
		}
		else if (!startMenuActive && bgMovie != null && bgMovie.isPlaying)
			bgMovie.Stop();
	}
	
	void Update(){
		if(Network.isServer && !startMenuActive){
			gameTimeElapsed += Time.deltaTime;
			if(gameTimeElapsed>gameLength&&endgameable){
				endgameable = false;
				networkstart.networkView.RPC("endGameRPC",RPCMode.AllBuffered,null);
			}
		}
	}
	
	
	public void setActive(bool isActive){
		startMenuActive = isActive;
	}
	
	public bool getActive(){
		return startMenuActive;
	}
	
	[RPC]
	public void setReady(bool ready,string ip){
		for (int i = 0; i < Network.connections.Length; i++){
			if (ip.Equals(Network.connections[i].ipAddress)){
				playersReady[i] = ready;
				break;
			}
		}
		Debug.Log("Entered setReady.");
	}
	
	[RPC]
	public void startClient(){
		networkstart.SpawnPlayer();
		startMenuActive = false;
		if (ductTape != null)
			ductTape.setDisplay(true);
		if (healthBar != null)
			healthBar.setDisplay(true);
	}
	
	bool allReady(){
		bool isEveryoneReady = true;
		for (int i = 0; i < playersReady.Count; i++){
			if (playersReady[i] == false)
				isEveryoneReady = false;
		}
		if (isEveryoneReady && selfReady)
			return true;
		else
			return false;
	}	
	
}

